/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package se.plingapp.backingbeans;

import java.util.Date;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import se.plingapp.enterprisebeans.UserFacade;
import se.plingapp.entitybeans.User;

/**
 *
 * @author Jens Ljungblad
 */
@ManagedBean
@RequestScoped
public class AuthBean {

    @EJB
    private UserFacade userFacade;

    private User user = new User();

    public User getUser() {
        return this.user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String login() {
        User dbUser = userFacade.findByEmail(user.getEmail());
        if(dbUser != null && dbUser.getPassword().equals(this.user.getPassword())) {
            dbUser.setLastLogin(new Date());
            userFacade.edit(dbUser);
            FacesContext fc = FacesContext.getCurrentInstance();
            fc.getExternalContext().getSessionMap().put("user", dbUser);
            return "/user/dashboard.xhtml?faces-redirect=true";
        } else {
            return "/start.xhtml?faces-redirect=true";
        }
    }

    public String logout() {
        FacesContext fc = FacesContext.getCurrentInstance();
        fc.getExternalContext().getSessionMap().put("user", null);
        return "/start.xhtml?faces-redirect=true";
    }
}
